# -*- coding: utf-8 -*-
from MyApi import *
import time
import configparser
import thosttraderapi as api
import os

#local config check check
if(os.path.exists("config.local.ini")):
	configfile = "config.local.ini"
else:
	configfile = "config.ini"

configins=configparser.ConfigParser()
configins.read(configfile)

#order config
INSTRUMENTLIST=configins['ordercon']['instrid'].split(',')
#PRICE=float(configins['ordercon']['limitprice'])
BUYPRICE=float(configins['ordercon']['bylmprice'])
SELLPRICE=float(configins['ordercon']['selmprice'])
PRICEOFFSET=float(configins['ordercon']['priceoffset'])

#stress config
autoprocess = configins['stressconfig']['autoprocess']
settleconfirm = configins['stressconfig']['settleconfirm']
closeposition = configins['stressconfig']['closeposition']


invlist = {}
invpasswd = {}
instrlist = {}
if(closeposition == "1"):
	if (EXCHANGEID in ['SHFE', 'INE']):
		offsetpara = 3
	else:
		offsetpara = 1
else:
	offsetpara = 0

if(os.path.exists("investorlist.local.txt")):
	investlistfile = "investorlist.local.txt"
else:
	investlistfile = "investorlist.txt"

def main():
	with open (investlistfile, 'r') as investorlist:
		typecount = 0
		for line in investorlist.readlines():
			(invid, passwd) = line.strip().split(",")
			if (typecount % 2 == 0):
				invlist[invid] = [None, 0, 0]
				invpasswd[invid] = passwd
			else:
				invlist[invid] = [None, 1, 0]
				invpasswd[invid] = passwd
			if(typecount == 0):
				firstinv = invid
			typecount += 1

	for instrid in INSTRUMENTLIST:
		instrlist[instrid] = {}
		instrlist[instrid]['buy'] = 0.0
		instrlist[instrid]['sell'] = 0.0

	#print(invlist)

	print("start login")
	for invid in sorted(invlist.keys()):
		invlist[invid][0] = CTradeApi()
		invlist[invid][0].start(invid, invpasswd[invid])
		while(1):
			if(invlist[invid][0].LoginCheck() == False):
				print("please wait for login")
				time.sleep(1)
			else:
				break
    
	print("login end!")

	if(autoprocess == "1"):
		print("auto next")
	else:
		input("press enter to continue")

	if(settleconfirm == "1"):
		print("start settle confirm")
		for invid in sorted(invlist.keys()):
			invlist[invid][0].ReqSettleInfoConfirm()
			while(1):
				if(invlist[invid][0].SettConfirmCheck() == False):
					print("please wait for settle confirm")
					time.sleep(1)
				else:
					break
		print("settle confirm end")


	print("start price setting")
	if(BUYPRICE == 0.0 or SELLPRICE == 0.0):
		invlist[firstinv][0].ReqQryInstr()
		while(1):
			if(invlist[firstinv][0].InstrQryCheck() == False):
				print("please wait for instrument query")
				time.sleep(1)
			else:
				instrcatch = invlist[firstinv][0].GetInstrQry() 
				break
		time.sleep(1)
		invlist[firstinv][0].ReqQryMD()
		while(1):
			if(invlist[firstinv][0].PriceQryCheck() == False):
				print("please wait for price query")
				time.sleep(1)
			else:
				pricecatch = invlist[firstinv][0].GetPriceQry() 
				break
		for instrid in instrlist.keys():
			if(instrid not in instrcatch.keys()):
				print(f"no instrument info for: {instrid}, del instrument!")
				del instrlist[instrid]

		for instrid in instrlist.keys():
			if(instrid in pricecatch.keys()):
				(lastprice, highprice, lowprice) = pricecatch[instrid]
				if(BUYPRICE == 0.0):
					currbuy = lastprice + PRICEOFFSET * instrcatch[instrid]
					if(currbuy < lowprice):
						instrlist[instrid]['buy'] = lowprice
					else:
						instrlist[instrid]['buy'] = currbuy
				else:
					instrlist[instrid]['buy'] = BUYPRICE + PRICEOFFSET * instrcatch[instrid]
				if(SELLPRICE == 0.0):
					currsell = lastprice - PRICEOFFSET * instrcatch[instrid]
					if(currsell > highprice):
						instrlist[instrid]['sell'] = highprice
					else:
						instrlist[instrid]['sell'] = currsell
				else:
					instrlist[instrid]['sell'] = SELLPRICE - PRICEOFFSET * instrcatch[instrid]
			else:
				print(instrid, 'has no marketdata! delete instrid:', instrid)
				del instrlist[instrid]
	else:
		for instrid in instrlist.keys():
			instrlist[instrid]['buy'] = BUYPRICE + PRICEOFFSET * instrcatch[instrid]
			instrlist[instrid]['sell'] = SELLPRICE - PRICEOFFSET * instrcatch[instrid]
	print("price setting end")
	print(instrlist)

	if(autoprocess == "1"):
		print("auto next")
	else:
		print("press enter to order gen!!!")
		print("press enter to order gen!!!")
		print("press enter to order gen!!!")
		input("press enter to order gen!!!")

	#print(invlist)
	while(1):
		for invid in sorted(invlist.keys()):
			dirt = invlist[invid][1]
			offsetflag = invlist[invid][2]
			for instrid in sorted(instrlist.keys()):
				originbuyprice = instrlist[instrid]['buy']
				originsellprice = instrlist[instrid]['sell']
				if(offsetflag != 0):
					if(dirt == 0):
						invlist[invid][0].OrderAction(instrid, originbuyprice, dirt, offsetflag)
					else:
						invlist[invid][0].OrderAction(instrid, originsellprice, dirt, offsetflag)
				else:
					if(dirt == 0):
						invlist[invid][0].OrderAction(instrid, originbuyprice, dirt, offsetflag)
					else:
						invlist[invid][0].OrderAction(instrid, originsellprice, dirt, offsetflag)
				time.sleep(oneturnsleep)
			invlist[invid][1] = invlist[invid][1]^1
			invlist[invid][2] = invlist[invid][2]^offsetpara



if __name__ == '__main__':
	main()